from stark.service.v1 import StarkHandler, StarkModelForm, get_date_format_text
from django.urls import re_path, reverse
from web import models
from django.utils.safestring import mark_safe
from django.shortcuts import HttpResponse, render
from django.forms.models import modelformset_factory


class CourseRecordModelForm(StarkModelForm):
    class Meta:
        model = models.CourseRecord
        fields = ['day_num', 'teacher']


class StudyRecordModelForm(StarkModelForm):
    class Meta:
        model = models.StudyRecord
        fields = ['record']


class CourseRecordHandler(StarkHandler):
    def display_attendance(self, obj=None, is_header=None, *args, **kwargs):
        """考勤记录链接"""
        if is_header:
            return '考勤'
        name = '%s:%s' % (self.site.namespace, self.get_urls_name('attendance'))
        url = reverse(name, kwargs={'course_record_id': obj.pk})
        return mark_safe('<a target="_blank" href="%s">考勤设置</a>' % url)

    field_name_list = [StarkHandler.display_checkbox, 'class_object', 'day_num', 'teacher',
                       get_date_format_text('上课时间', 'date'), display_attendance]
    model_form_class = CourseRecordModelForm

    def display_edit_del(self, obj=None, is_header=None, *args, **kwargs):
        """编辑删除 在一列显示"""
        """自定值编辑删除 反向生成url 携带的参数是class_id"""
        class_id = kwargs.get('class_id')
        if is_header:
            return '操作'
        tmp = '<a href="%s" class="glyphicon glyphicon-edit" style="color:darkgrey"></a> &nbsp;&nbsp;<a href="%s" ' \
              'class="glyphicon glyphicon-trash" style="color:red"></a>' % (
                  self.reverse_edit_url(pk=obj.pk, class_id=class_id),
                  self.reverse_del_url(pk=obj.pk, class_id=class_id))
        return mark_safe(tmp)

    def get_urls(self):
        patterns = [
            re_path('list/(?P<class_id>\d+)/', self.wrapper(self.changelist_view), name=self.get_list_url_name),
            re_path('add/(?P<class_id>\d+)/', self.wrapper(self.add_view), name=self.get_add_url_name),
            re_path('edit/(?P<class_id>\d+)/(?P<pk>\d+)/', self.wrapper(self.edit_view), name=self.get_edit_url_name),
            re_path('del/(?P<class_id>\d+)/(?P<pk>\d+)/', self.wrapper(self.del_view), name=self.get_del_url_name),
            re_path('attendance/(?P<course_record_id>\d+)/', self.wrapper(self.attendance_view),
                    name=self.get_urls_name('attendance')),
        ]
        patterns.extend(self.extra_urls())  # 新增的url 扩增
        return patterns

    def get_queryset(self, request, *args, **kwargs):
        class_id = kwargs.get('class_id')
        return self.model_class.objects.filter(class_object_id=class_id)

    def save(self, request, form, is_update, *args, **kwargs):
        is_update = False
        class_id = kwargs.get('class_id')
        # 添加页面 填写默认值
        if not is_update:
            form.instance.class_object_id = class_id
            form.save()

    def multi_init_study_records(self, request, *args, **kwargs):
        """
        批量初始化考勤记录

        获取当前课程，当前节次所有学生的上课记录，保存到数据库中
        """
        # 选中的课程上课节次的id
        course_record_id_list = request.POST.getlist('pk')
        # 获取 班级的id,同时找到此班级下的所有学生
        class_id = kwargs.get('class_id')
        # 判断班级是否存在
        class_obj = models.ClassList.objects.filter(id=class_id).first()
        if not class_obj:
            return HttpResponse('班级不存在')

        # 获取班级下所有的学生对象
        student_obj_list = class_obj.student_set.all()

        # 验证上课记录
        for course_record_id in course_record_id_list:
            # 判断上课记录是否合法
            course_record_obj = models.CourseRecord.objects.filter(id=course_record_id,
                                                                   class_object_id=class_id).first()
            if not course_record_obj:
                continue
            # 判断选中的节次的考勤记录是否存在
            study_obj = models.StudyRecord.objects.filter(course_record=course_record_obj).exists()
            if study_obj:
                continue
            # 若不存在为每个学生创建考勤记录
            # for student in student_obj_list:
            #     models.StudyRecord.objects.create(student_id=student.id, course_record_id=course_record_id)

            # 批量创建
            study_record_obj_list = [models.StudyRecord(student_id=student.id,
                                                        course_record_id=course_record_id) for student in
                                     student_obj_list]
            models.StudyRecord.objects.bulk_create(study_record_obj_list, batch_size=50)

    multi_init_study_records.text = '批量初始化考勤'
    action_list = [multi_init_study_records, ]

    def attendance_view(self, request, course_record_id, *args, **kwargs):
        """考勤的批量设置"""

        study_record_obj_list = models.StudyRecord.objects.filter(course_record_id=course_record_id)
        # 创建formset
        study_modelformset=modelformset_factory(models.StudyRecord, form=StudyRecordModelForm, extra=0)
        # 实例化formset
        formset = study_modelformset(queryset=study_record_obj_list)
        if request.method == 'POST':
            formset = study_modelformset(queryset=study_record_obj_list,data=request.POST)
            if formset.is_valid():
                formset.save()
            return render(request, 'attendance.html', {'formset': formset})
        return render(request,'attendance.html',{'formset':formset})
